package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 设置通过拦截器保护请求
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.csrf().disable();//禁用跨域保护策略csrf。csrf默认开启，这样就得在登录时加个_csrf参数，演示环境可以禁用

        //认证需求路径
        http.authorizeRequests()
                .antMatchers("/", "/home")//添加ant风格的url匹配
                .permitAll()//上面两个url全部允许（放行）
                .anyRequest()//任何请求url
                .authenticated();//都需要验证

        //登录路径
        http.formLogin()
                .loginPage("/signin")//登录界面，未登录会跳转到这个url，若controller未配置对应url，会默认跳转一个的html登陆界面
                .loginProcessingUrl("/dosignin")//登录接口，通过这个接口实现登录，若未设置，则会将loginPage的设置url作为默认登录接口
                .failureUrl("/error")//登录错误跳转
                .defaultSuccessUrl("/hello")//登录成功跳转
                .permitAll();//全部放行

        //登出路径
        http.logout()
                .logoutSuccessUrl("/home")//登出成功跳转
                .logoutUrl("/logout");//登出url
    }





    /**
     * 生成一个内存用户
     * @return
     */
    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()//处于演示可用，生产环境由于不安全而不建议使用
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}
